<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\CustomerDelivery;

use App\Func\UploadFile;
use App\Models\Basics\ExpressCompany;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysPlat;
use App\Models\CustomerDelivery\CustomerDelivery;
use App\Models\CustomerDelivery\CustomerDeliveryDetail;
use App\Models\CustomerDelivery\CustomerDeliveryLogistics;
use App\Models\CustomerDelivery\CustomerOrder;
use App\Models\CustomerDelivery\CustomerOrderDetails;
use App\Util\SerialNo;
use App\Models\Inventory\AreaCn;
use App\Models\Inventory\InventoryCn;
use App\Models\Inventory\Record;
use App\Models\Inventory\Placing;
use App\Models\Inventory\Timely;
use App\Models\Product\ProductSku;
use App\Models\Sys\Logs;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;

class DeliveryCnAjax {

    /**
     * 匹配创建订单所需的产品信息
     * @param $param
     * @return false|string
     */
    public function matchDetailInfo($param){
        //获取国家对应的发货站点
        $areaId = SysCountry::getAreaIdByCountryId($param['country_id']);
        $pSkuCn = ProductSku::getValueById($param['psku_id'], 'psku_cn');
        $instant = AreaCn::getInstant($areaId, $param['psku_id']);
        $sumInstant = Timely::getInstant($param['psku_id']);
        return json_encode(['psku_cn'=>$pSkuCn ?: $param['psku_id'], 'instant' => $instant, 'sum_instant' => $sumInstant]);
    }

    /**
     * 创建国内订单
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function createOrder($param){

        $receiver = $param['receiver'];
        $detail = $param['detail'];
        $orderChannel = isset($param['order_channel']);
        $orderType = isset($param['order_type']);
        $platId = $param['plat_id'];
        $countryId = $param['country_id'];
        if(!$countryId || !$orderChannel || !$orderType || !isset($platId)){
            return response()->json(['status' => false, 'message' => '订单参数必选,不能为空!']);
        }
        if (!in_array(isset($platId), SysPlat::options()->toArray())) {
            return response()->json(['status' => false, 'message' => '平台异常!']);
        }

        //获取国家
        $countryObj = SysCountry::getModelById($countryId);
        if(empty($countryObj)) return response()->json(['status' => false, 'message' => '发货国家异常!']);
        //获取国家对应的发货站点
        $areaId = SysCountry::getAreaIdByCountryId($countryObj->id);
        if(empty($areaId)) return response()->json(['status' => false, 'message' => '发货站点异常!']);

        $error = [];
        $orderDetailData = [];
        foreach($detail as $item) {
            //验证sku
            $pSkuId = $item['psku_id'];
            $applyNum = intval($item['apply_num']);
            $num = AreaCn::getInstant($areaId, $pSkuId); //可发库存
            $ps = ProductSku::getModelById($pSkuId);
            if ($num < $applyNum) {
                $error[] = $ps->psku_code . '可发库存：' . $num;
                continue;
            }
            //订单明细
            $orderDetailData[] = [
                'plat_id'   => $platId,
                'psku_id'   => $pSkuId,
                'order_num' => $applyNum,
                'apply_num' => $applyNum,
                'status'    => CustomerOrderDetails::ORDER_DELIVERY_YES, //订单状态 3: 完全申请
                'is_create' => CustomerOrderDetails::CREATE_YES, //是否为自建订单 (0：自动生成订单 1：真实自建订单)
                'sync_status' => CustomerOrder::SYNC_YES //已同步
            ];
        }
        if(!empty($error)) return response()->json(['status' => false, 'message' => implode(PHP_EOL, $error).'可发库存不足']);

        $orderNo = trim($param['order_no']) ?: SerialNo::getOCnNo();  //客户订单(国内erp手工自建单)，生成客户订单号
        $orderCount = CustomerOrder::query()->where(['order_no' => $orderNo])->count();
        if($orderCount > 0) return response()->json(['status' => false, 'message' => '订单号已存在, 请重新选择单号']);

        //DB::beginTransaction();
        //try{
            //收货人信息
            $_receiver = [
                'country'    => $receiver['country'],
                'receiver'   => $receiver['receiver'],
                'address'    => $receiver['address'],
                'state'      => $receiver['state'],
                'city'       => $receiver['city'],
                'postcode'   => $receiver['postcode'],
                'phone'      => $receiver['phone'],
            ];
            //创建相关订单信息
            $orderObj = CustomerOrder::query()->create([
                'order_no'      => $orderNo,
                'order_at'      => date('Y-m-d H:i:s', time()),
                'order_channel' => $orderChannel,   //订单渠道(1.C端，2.B端)
                'order_type'    => $orderType,  //订单类型(1.订单，2.寄样)
                'plat_id'       => $platId, //订单平台(0:无 1:FBA亚马逊 2:shopify 3:乐天)
                'area_id'       => $areaId, //发货站点
                'country_id'    => $countryObj->id, //发货国家
                'country_code'  => $countryObj->country, //国家编码
                'is_create'     => CustomerOrderDetails::CREATE_YES, //是否为自建订单 (0：自动生成订单 1：真实自建订单)
                'sync_status'   => CustomerOrder::SYNC_YES //已同步
            ]);
            $orderObj->receiver()->create($_receiver);
            $orderObj->detail()->createMany($orderDetailData);
            if(!$orderObj) return response()->json(['status' => false, 'message' => '订单录入失败']);
            Logs::logs('customer-order-cn', "创建国内订单(自建)：{$orderNo}", $orderObj->id);

            $flag = false;
            $deliveryDetailData = [];
            foreach($orderObj->detail as $_item){
                //发货明细
                $deliveryDetailData[] = [
                    'order_no'          => $orderNo,
                    'delivery_order_no' => $orderNo,
                    'order_detail_id'   => $_item->id,
                    'plat_id'           => $platId,
                    'psku_id'           => $_item->psku_id,
                    'apply_num'         => $_item->apply_num,
                    'delivery_type' => CustomerDelivery::DELIVERY_TYPE_CN,   //发货方式 (3:国内)
                ];
                //更新国内库存
                $inventoryCnFlag = DeliveryDemandAjax::saveCnInventory($_item->toarray(), $orderNo);
                if ($inventoryCnFlag == false) break;

                $flag = true;
            }
            if(!$flag) return response()->json(['status' => false, 'message' => '库存更新失败']);

            //创建相关发货信息
            $deliveryNo = SerialNo::getOPDNo(); //国内自建订单,生成发货单号
            $deliveryObj = CustomerDelivery::query()->create([
                'delivery_no' => $deliveryNo,
                'order_no' => $orderNo,
                'order_at' => date('Y-m-d H:i:s', time()),
                'plat_id'  => $platId, //订单平台(0:无 1:FBA亚马逊 2:shopify 3:乐天)
                'area_id' => $areaId,
                'country_id' => $countryObj->id,
                'seller_id' => Admin::user()->id ?? 1,
                'delivery_type' => CustomerDelivery::DELIVERY_TYPE_CN,   //发货方式 (3:国内)
                'status' => CustomerDelivery::STATUS_READY_NO,          //发货状态 (1:待备货)
                'logistics_status' => CustomerDelivery::LOGISTICS_STATUS_NO, //物流状态 (1:待更新)
            ]);
            $_receiver['cpf'] = $receiver['cpf'];
            $deliveryObj->receiver()->create($_receiver);
            $deliveryObj->detail()->createMany($deliveryDetailData);
            if(!$deliveryObj) return response()->json(['status' => false, 'message' => '操作失败']);

            //添加日志
            Logs::logs('customer-order-cn', "创建国内发货单：{$deliveryNo}", $deliveryObj->id);

            //DB::commit();
            return response()->json(['status' =>true, 'message' => '操作成功!']);

        //}catch (\Exception $e){
        //    DB::rollBack();
        //    report($e);
        //    return response()->json(['status' => false, 'message' => $e->getMessage()]);
        //}
    }

    /**
     * 编辑
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function listEdit($id){
        $delivery = CustomerDelivery::query()->find($id);
        return view('customer-delivery.delivery-cn.modal-edit',compact('id','delivery'));
    }

    public function doListEdit($param){
        try{
            DB::beginTransaction();

            $deliveryObj = CustomerDelivery::query()->find($param['id']);
            if($deliveryObj->status == CustomerDelivery::STATUS_DELIVERY_YES) throw new \Exception('发货单状态有误!');

            $orderObj = CustomerOrder::query()->where('order_no', $deliveryObj->order_no)->first();
            if(empty($orderObj)) throw new \Exception('订单异常!');

            $receiverFields = ['country','receiver','address','state','city','postcode','phone','cpf'];
            foreach($param as $k => $v){
                if(in_array($k, $receiverFields)){

                    $deliveryObj->receiver->{$k} = $v;

                    if ($k == 'cpf')  break; //订单表中没有cpf字段,所以参数存在该字段则跳过，cpf字段不更新
                    $orderObj->receiver->{$k} = $v;
                }
            }

            //更新地址
            if(!$deliveryObj->receiver->save()) throw new \Exception('编辑地址失败!');

            //更新订单
            if(!$orderObj->receiver->save()) throw new \Exception('编辑订单失败!');

            //添加日志
            Logs::logs('customer-order-cn', "国内发货单：{$deliveryObj->delivery_no} 编辑收货人信息", $deliveryObj->id);
            DB::commit();
            return response()->json(['status' =>true, 'message' => '编辑成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

    /**
     * 开始备货
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function listStartPreparing($id){

        $delivery = CustomerDelivery::query()->findOrFail($id);
        $status = $delivery->status;
        if($delivery && $delivery->status == CustomerDelivery::STATUS_READY_NO){
            try{
                DB::beginTransaction();
                $delivery->status = CustomerDelivery::STATUS_READY_YES; //发货状态 (2:已备货)
                if(!$delivery->save()) {
                    DB::rollBack();
                }else{
                    //更新发货明细
                    CustomerDeliveryDetail::query()
                        ->where('delivery_no', $delivery->delivery_no)
                        ->update([
                            'status' => CustomerDelivery::STATUS_READY_YES, //发货状态 (2:已备货)
                        ]);

                    Logs::logs('customer-order-cn', "国内发货单：{$delivery->delivery_no} 开始备货", $id);
                    DB::commit();
                }
            }catch (\Exception $e){
                report($e);
            }
        }
        return view('customer-delivery.delivery-cn.modal-prepare',compact('id','delivery','status'));
    }

    /**
     * 开始备货（view状态）
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function listPreparing($id){

        $delivery = CustomerDelivery::query()->findOrFail($id);
        $status = $delivery->status;

        return view('customer-delivery.delivery-cn.modal-prepare',compact('id','delivery','status'));
    }

    /**
     * 开始备货（操作）
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function doListPrepare($param){
        DB::beginTransaction();
        try{
            $delivery = CustomerDelivery::query()->find($param['id']);
            if($delivery->status != CustomerDelivery::STATUS_READY_YES){
                return response()->json(['status' => false, 'message' => '发货单状态有误1!']);
            }


            $flag = false;
            $detail = $param['detail'];
            foreach ($detail as $item){
                $deliveryDetailObj = CustomerDeliveryDetail::query()->find($item['id']);
                $deliveryDetailObj->ship_num += $item['ship_num'];
                if($deliveryDetailObj->ship_num < 0) $deliveryDetailObj->ship_num = 0;
                if(!$deliveryDetailObj->save()){
                    break;
                }
                $flag = true;
            }
            if(!$flag) throw new \Exception('操作失败!');

            Logs::logs('customer-order-cn', "国内发货单：{$delivery->delivery_no} 备货中", $delivery->id);
            DB::commit();
            return response()->json(['status' =>true, 'message' => '操作成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

    /**
     * 备货完成
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function packetPrepared($id){
        try{
            $delivery = CustomerDelivery::query()->find($id);
            if($delivery->status != CustomerDelivery::STATUS_READY_YES){
                return response()->json(['status' => false, 'message' => '发货单状态有误2!']);
            }

            DB::beginTransaction();
            //更新发货
            $delivery->status = CustomerDelivery::STATUS_DELIVERY_NO; //发货状态 (3:待发货)
            if(!$delivery->save())  throw new \Exception('备货失败!');

            //更新发货明细
            $deliveryDetailObj = CustomerDeliveryDetail::query()
                ->where('delivery_no', $delivery->delivery_no)
                ->update([
                    'status' => CustomerDelivery::STATUS_DELIVERY_NO
                ]);
            if(!$deliveryDetailObj) throw new \Exception('备货明细失败!');

            //日志
            Logs::logs('customer-order-cn', "国内发货单：{$delivery->delivery_no} 备货完成", $delivery->id);
            DB::commit();
            return response()->json(['status' =>true, 'message' => '备货成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

    /**
     * 返回备货
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function backPreparing($id){
        try{
            $delivery = CustomerDelivery::query()->find($id);
            if(!in_array($delivery->status, [CustomerDelivery::STATUS_READY_YES, CustomerDelivery::STATUS_DELIVERY_NO])){
                return response()->json(['status' => false, 'message' => '发货单状态有误3!']);
            }

            //更新发货
            DB::beginTransaction();
            $delivery->status = CustomerDelivery::STATUS_READY_NO; //发货状态 (1:待备货)
            if(!$delivery->save()) throw new \Exception('返回备货失败!');

            //更新发货明细
            $deliveryDetailObj = CustomerDeliveryDetail::query()
                ->where('delivery_no', $delivery->delivery_no)
                ->update([
                    'status' => CustomerDelivery::STATUS_READY_NO
                ]);
            if(!$deliveryDetailObj) throw new \Exception('返回备货明细失败!');

            //日志
            Logs::logs('customer-order-cn', "国内发货单：{$delivery->delivery_no} 返回重新备货", $delivery->id);
            DB::commit();
            return response()->json(['status' => true, 'message' => '返回备货成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

    /**
     * 发货
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function ship($id){
        $delivery = CustomerDelivery::query()->findOrFail($id);
        return view('customer-delivery.delivery-cn.modal-ship',compact('id','delivery'));
    }

    /**
     * 发货
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function doShip($id){
        //DB::beginTransaction();
        //try{
            $delivery = CustomerDelivery::query()->findOrFail($id);
            if(!$delivery || $delivery->status != CustomerDelivery::STATUS_DELIVERY_NO){
                return response()->json(['status' => false, 'message' => '发货单有误!']);
            }

            $flag1 = false;
            $placingDetail = [];

            foreach($delivery->detail as $k => $detail){
                //出库明细
                $placingDetail[$k]['order_no']     = $detail->delivery_no; //发货单号
                $placingDetail[$k]['detail_id']    = $detail->id;
                $placingDetail[$k]['psku_id']      = $detail->psku_id;
                $placingDetail[$k]['placing_num']  = $detail->ship_num;

                //库存差额数据回写
                $flag2 = $this->_shipRewrite(Admin::user()->id, $delivery->area_id, $detail->psku_id, $detail->apply_num, $detail->ship_num);
                if(!$flag2){
                    $flag1 = false;
                    break;
                }

                $flag1 = true;
            }
            if(!$flag1) return response()->json(['status' => false, 'message' => '操作失败1!']);

            //更新发货单
            $delivery->status = CustomerDelivery::STATUS_DELIVERY_YES; //发货状态 (5:已发货)
            $delivery->delivered_at = date('Y-m-d H:i:s');
            if(!$delivery->save()) return response()->json(['status' => false, 'message' => '操作失败2!']);

            //更新发货明细
            $deliveryDetailObj = CustomerDeliveryDetail::query()
                ->where('delivery_no', $detail->delivery_no)
                ->where('status', CustomerDeliveryDetail::STATUS_DELIVERY_NO) //发货单状态 (3:待发货)
                ->where('delivery_type', CustomerDelivery::DELIVERY_TYPE_CN) //发货方式 (3:国内)
                ->update([
                    'status' =>CustomerDeliveryDetail::STATUS_DELIVERY_YES, //发货明细状态 (5:已发货)
                    'delivered_at' => $delivery->delivered_at ?? date('Y-m-d H:i:s') //发货时间
                ]);
            if(!$deliveryDetailObj) return response()->json(['status' => false, 'message' => '操作失败2-1!']);

            //库存出库相关信息
            $placing = Placing::query()->create([
                'placing_no' => SerialNo::getPlNo(),
                'placing_at' => date('Y-m-d'),
                'cuser_id' => Admin::user()->id
            ]);
            $placing->detail()->createMany($placingDetail);
            if(!$placing) return response()->json(['status' => false, 'message' => '操作失败3!']);

            //日志
            Logs::logs('customer-order-cn', "国内发货单：{$delivery->delivery_no} 已发货", $id);

            //DB::commit();
            return response()->json(['status' => true,'message' => '发货成功!']);

        //}catch (\Exception $e){
        //    DB::rollBack();
        //    report($e);
        //    return response()->json(['status' => false, 'message' => $e->getMessage()]);
        //}
    }

    /**
     * *发货*
     * 库存差额数据回写
     * @param $userId
     * @param $areaId
     * @param $pSkuId
     * @param $applyNum
     * @param $shipNum
     * @return bool
     */
    private function _shipRewrite($userId, $areaId, $pSkuId, $applyNum, $shipNum){
        //更新国内库存
        $inventoryObj = InventoryCn::query()->firstOrNew([
            'area_id' => $areaId,
            'psku_id' => $pSkuId
        ],[
            'reserve' => 0,
            'instant' => 0
        ]);
        if(!$inventoryObj){
            return false;
        }
        $inventoryObj->reserve -= min($inventoryObj->reserve, $applyNum);
        $inventoryObj->instant += $applyNum - $shipNum;
        if(!$inventoryObj->save()){
            return false;
        }

        //添加记录
        $flag2 = Record::query()->create([
            'record_no' => SerialNo::getRcNo(),
            'psku_id' => $pSkuId,
            'area_id' => $areaId,
            'action_type' => 4,
            'record_type' => 2,
            'num' => -$shipNum,
            'user_id' => $userId,
        ]);
        if(!$flag2){
            return false;
        }
        return true;
    }

    //更新物流
    public function listLogistics($id){
        $delivery = CustomerDelivery::query()->findOrFail($id);
        return view('customer-delivery.delivery-cn.modal-logistics',compact('id','delivery'));
    }

    public function doLogistics($param){

        $deliveryObj = CustomerDelivery::query()->findOrFail($param['id']);
        if($deliveryObj->status != CustomerDelivery::STATUS_DELIVERY_YES){
            return response()->json(['status' => false, 'message' => '发货单状态有误!']);
        }

        //乐天（rakuten）
        if ($deliveryObj->plat_id == SysPlat::PLAT_RAKUTEN) {
            if(!$param['tracking_no'] || !$param['express_company_id'] || !$param['delivered_at']){
                return response()->json(['status' => false, 'message' => '请补全乐天物流信息（追踪号、物流公司、发货时间）!']);
            }
            $expressCompany = ExpressCompany::getModel($param['express_company_id']);
            if(!$expressCompany){
                return response()->json(['status' => false, 'message' => '物流公司不存在!']);
            }
            if (empty($expressCompany->name_en)) {
                return response()->json(['status' => false, 'message' => '物流公司异常：未配置名称(日文)!']);
            }
            //（补充乐天平台物流信息）
            $paramData['logistics_type'] = $expressCompany->name_en; //乐天物流公司（日文名称）
            $paramData['delivered_at'] = $param['delivered_at'] ?? date('Y-m-d H:i:s', time());  //发货时间
        }

        if (!isset($param['delivered_at'])){ //发货时间不存在，则默认发货时间
            $param['delivered_at'] = date('Y-m-d H:i:s', time());
        }
        $paramData['shipping_date'] = date('Y-m-d', strtotime($param['delivered_at']));
        $paramData['tracking_no'] = $param['tracking_no'];
        $paramData['total_weight'] = $param['total_weight'] ?? 0;
        $paramData['shipping_fee'] = $param['shipping_fee'] ?? 0;
        $paramData['other_fee']  = $param['other_fee'] ?? 0;
        if (intval($param['total_weight']) > 0 || intval($param['total_weight']) > 0 || intval($param['other_fee']) > 0) {
            $paramData['logistics_fee_status'] = CustomerDeliveryDetail::LOGISTICS_FEE_YES;  //物流费用，已更新 (0:未更新 1:已更新)
        }
        if ($param['tracking_no']) {
            $paramData['sync_status'] = CustomerDeliveryDetail::SYNC_STATUS_YES; //物流追踪号同步，已同步 (0:未同步 1:已同步)
        }

        DB::beginTransaction();
        try{
            //更新国内发货物流
            CustomerDeliveryLogistics::query()->updateOrCreate(
                ['delivery_no' => $deliveryObj->delivery_no],
                [
                    'order_no'    => $deliveryObj->order_no,
                    'express_company_id' => $param['express_company_id'] ?? null,
                    'area_id'            => $param['area_id'] ?? null,
                    'express_channel_id' => $param['express_channel_id'] ?? null,
                    'tracking_no'        => $param['tracking_no'] ?? null,
                    'total_weight'       => $param['total_weight'] ?? 0,
                    'shipping_fee'       => $param['shipping_fee'] ?? 0,
                    'other_fee'          => $param['other_fee'] ?? 0,
                    'delivered_at'       => $param['delivered_at'] ?? null,
                    'arrived_at'         => $param['arrived_at'] ?? null,
                ]
            );

            //更新发货明细
            $deliveryDetailObj = CustomerDeliveryDetail::query()
                ->where('delivery_no', $deliveryObj->delivery_no)
                ->update($paramData);
            if(!$deliveryDetailObj){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '发货明细,更新失败!']);
            }

            //更新发货单
            $deliveryObj->logistics_status = CustomerDelivery::LOGISTICS_STATUS_YES; //物流状态 (2:已更新)
            if(!$deliveryObj->save()) throw new \Exception('更新失败!');

            //更新日志
            Logs::logs('customer-order-cn', "发货单：{$deliveryObj->delivery_no} 物流信息已更新", $deliveryObj->id);
            DB::commit();
            return response()->json(['status' =>true, 'message' => '物流更新成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

    /**
     * 删除发货单
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function delDelivery($id){

        $deliveryObj = CustomerDelivery::query()->findOrFail($id);
        if(!$deliveryObj || $deliveryObj->status != CustomerDelivery::STATUS_READY_NO){
            return response()->json(['status' => false, 'message' => '发货单异常!']);
        }

        $orderObj = CustomerOrder::query()->where(['order_no'=>$deliveryObj->order_no])->first();
        if (!$orderObj){
            return response()->json(['status' => false, 'message' => '客户订单异常!']);
        }

        DB::beginTransaction();
        try{
            $flag = false;
            foreach($deliveryObj->detail as $detail){

                //回写库存（国内）
                $inventoryObj = InventoryCn::query()->firstOrNew([
                    'area_id' => $deliveryObj->area_id,
                    'psku_id' => $detail->psku_id
                ],[
                    'reserve' => 0,
                    'instant' => 0
                ]);
                $inventoryObj->reserve -= min($inventoryObj->reserve, $detail->apply_num);
                $inventoryObj->instant += $detail->apply_num;
                $flag1 = $inventoryObj->save();
                if(!$flag1){
                    $flag = false;
                    break;
                }

                //回写订单
                $flag2 = $this->_outOrderDetailRewriteForDel($detail->order_detail_id, $detail->apply_num);
                if(!$flag2){
                    $flag = false;
                    break;
                }
                $flag = true;
            }
            if(!$flag) throw new \Exception('数据回写失败!');


            //订单为(国内)手动自建订单时,删除发货单相关信息 (包括客户主订单)
            if ($orderObj->is_create == CustomerOrder::CREATE_YES) {
                //手动自建(国内),同时删除发货单和客户主订单
                if(!$deliveryObj->delete()) throw new \Exception('删除失败-1!');
                if(!$orderObj->delete()) throw new \Exception('删除失败-2!');
            }else{
                //非手动自建(国内),只删除发货单
                if(!$deliveryObj->delete()) throw new \Exception('删除失败!');
            }

            //日志
            Logs::logs('customer-order-cn', "国内发货单：{$deliveryObj->delivery_no} 已删除", $id);
            DB::commit();
            return response()->json(['status' => true, 'message' => '删除成功!']);

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => $e->getMessage()]);
        }
    }

    /**
     * 站外订单数据回写（删除）
     * @param $orderDetailId
     * @param $applyNum
     * @return bool
     */
    private function _outOrderDetailRewriteForDel($orderDetailId, $applyNum){

        $orderDetailObj = CustomerOrderDetails::query()->find($orderDetailId);
        if(!$orderDetailObj)return false;

        //更新订单明细
        $orderDetailObj->apply_num -= $applyNum;
        if($orderDetailObj->apply_num < 0){
            $orderDetailObj->apply_num = 0;
        }

        $num = $orderDetailObj->apply_num;
        if($num == 0){
            $orderDetailObj->status =  CustomerOrderDetails::ORDER_DELIVERY_NO;    //1:未申请
        }else{
            if($orderDetailObj->order_num > $num){
                $orderDetailObj->status = CustomerOrderDetails::ORDER_DELIVERY_PART;    //2:部分申请
            }else{
                $orderDetailObj->status = CustomerOrderDetails::ORDER_DELIVERY_YES;    //3:完全申请
            }
        }
        if(!$orderDetailObj->save()){
            return false;
        }

        return true;
    }

    //上传发货备注图片
    public function RemarkImages($id){
        $delivery = CustomerDelivery::query()->findOrFail($id);
        return view('customer-delivery.delivery-cn.modal-images',compact('id','delivery'));
    }

    //处理，上传发货备注图片
    public function doRemarkImages($param){
        if($param['file']->isValid()){
            $file = $param['file'];
            try{
                DB::beginTransaction();
                $deliveryObj = CustomerDelivery::query()->findOrFail($param['id']);
                if(!$deliveryObj) throw new \Exception('发货单异常!');

                $fileDir = 'deliveryImage/'.date('Ymd',time()); //文件夹
                $imageName = $deliveryObj->delivery_no.'_+'.$file->getClientOriginalName(); //文件名

                $uploadFile = UploadFile::getInit();
                if(!$uploadFile->upload($file, $fileDir, false,$imageName)){
                    return response()->json(['status' => false, 'message' => '操作失败！']);
                }else{
                    $remarkImages = $fileDir.'/'.$imageName; //图片路径（deliveryImage/20230910/OPD23070600001.jpg）
                    $deliveryObj->remark_images = $remarkImages;
                    if(!$deliveryObj->save()){
                        DB::rollBack();
                        return response()->json(['status' => false, 'message' => '上传失败！']);
                    }else{
                        DB::commit();
                        return response()->json(['status' => true, 'message' => '上传成功！']);
                    }
                }
            }catch (\Exception $e){
                DB::rollBack();
                report($e);
                return response()->json(['status' => false, 'message' => '系统异常！']);
            }
        }else{
            return response()->json(['status' => false, 'message' => '无效文件！']);
        }
    }

    /**
     * 删除图片
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteImages($id){

        $deliveryObj = CustomerDelivery::query()->find($id);
        if(!$deliveryObj){
            return response()->json(['status' => false, 'message' => '发货单异常！']);
        }

        $uploadFile = UploadFile::getInit();
        if(!$uploadFile->delFile($deliveryObj->remark_images)){ //图片路径（deliveryImage/20230910/OPD23070600001.jpg）
            return response()->json(['status' => false, 'message' => '删除失败！']);
        }else{
            $deliveryObj->remark_images = null;
            if(!$deliveryObj->save()){
                return response()->json(['status' => false, 'message' => '删除失败！']);
            }else{
                return response()->json(['status' => true, 'message' => '删除成功！']);
            }
        }
    }

}
